﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace MarketDataAnalyzer
{
    public class PriceAnalysis
    {
        public DateTime NewsEventTimeEst { get; set; }

        public int NewsId { get; set; }

        public string Symbol { get; set; }

        public int MatchingNewsId { get; set; }

        public IEnumerable<PricePoint> ActualPricePoints { get; set; }

        public IList<ProjectedPriceAnalysis> ProjectedPriceAnalyses { get; set; }

        public decimal GetActualPriceAtRelativeTime( int minutesRelativeToNewsEvent )
        {
            return
                ActualPricePoints.Where( pp => pp.Time >= NewsEventTimeEst.AddMinutes( minutesRelativeToNewsEvent ) )
                .Select( pp => pp.Price )
                .FirstOrDefault();
        }

        public decimal GetActualChangeInPercentAfterEvent(int minutesRelativeToNewsEvent)
        {
            if (minutesRelativeToNewsEvent < 0)
            {
                return 0.0m;
            }

            var priceAtEvent = GetActualPriceAtRelativeTime( 0 );
            var priceAtTime = GetActualPriceAtRelativeTime( minutesRelativeToNewsEvent );

            if (priceAtEvent == 0.0m)
            {
                return priceAtEvent;
            }

            return (priceAtTime - priceAtEvent) / priceAtEvent;
        }

        public decimal GetProjectedChangeInPercent(int minutesRelativeToNewsEvent)
        {
            if (minutesRelativeToNewsEvent < 0)
            {
                return 0.0m;
            }

            var percentageChanges = new List<decimal>();
            foreach ( var projectedPriceAnalysis in ProjectedPriceAnalyses)
            {
                var priceAtEvent = projectedPriceAnalysis.GetPriceAtRelativeTime( 0 );
                if (priceAtEvent == 0)
                {
                    continue;
                }
                var priceAtTime = projectedPriceAnalysis.GetPriceAtRelativeTime( minutesRelativeToNewsEvent );

                percentageChanges.Add( (priceAtTime - priceAtEvent) / priceAtEvent );
            }

            if (percentageChanges.Count == 0)
            {
                percentageChanges.Add( 0.0m );
            }
            return percentageChanges.Average();
        }

        public override string ToString()
        {
            return string.Format( "Price Analysis for {0} at {1}", Symbol, NewsEventTimeEst );
        }

        public PriceAnalysis()
        {
            ActualPricePoints = new List<PricePoint>();
            ProjectedPriceAnalyses = new List<ProjectedPriceAnalysis>();
        }
    }
}
